package com.itheima.controller.admin;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.dto.*;
import com.itheima.properties.JwtProperties;
import com.itheima.result.Result;
import com.itheima.service.IEmployeeService;
import com.itheima.service.IShipDataService;
import com.itheima.ship.po.Employee;
import com.itheima.ship.po.ShipData;
import com.itheima.utils.JwtUtil;
import com.itheima.vo.EmployeeLoginVO;
import com.itheima.vo.PageResultVO;
import com.itheima.vo.ShipVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.AccountException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郑哥
 * @since 2024-05-18
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "员工管理接口")
@Slf4j
public class EmployeeController {
    @Autowired
    private IShipDataService shipDataService;

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation("员工登录")
    public Result<EmployeeLoginVO> employeeLogin(@RequestBody EmployeeLoginDTO employeeLoginDTO) throws AccountException {
        log.info("员工登录请求参数：{}", employeeLoginDTO);
        Employee employee = employeeService.getEmployeeByUsernameAndPassword(employeeLoginDTO);
        Map<String, Object> claims = new HashMap<>();
        claims.put("empId", employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(), claims);

        System.out.println(token);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();


        return Result.success(employeeLoginVO);
    }


    /*
     * 进入首页后查询全部数据显示到页面
     * */
    @GetMapping("/selectById/{id}")
    @ApiOperation("查询所有数据接口")
    public Result<ShipVO> selectById(@PathVariable Long id) {
        ShipData shipData = shipDataService.getById(id);
        ShipVO shipVO = BeanUtil.copyProperties(shipData, ShipVO.class);
        return Result.success(shipVO);
    }


    /*
     * 员工退出登录
     * */

    @PostMapping("/logout")
    @ApiOperation("员工退出")
    public Result<String> logout() {
        return Result.success();
    }

    @PostMapping("/register")
    @ApiOperation("员工注册")
    public Result registerEmployee(@RequestBody EmployeeRegisterDTO employeeRegisterDTO) throws AccountException {
        log.info("员工注册请求参数：{}", employeeRegisterDTO);
        employeeService.registerEmployee(employeeRegisterDTO);
        return Result.success();
    }

    /**
     * 生成验证码
     *
     * @param response
     */
    @GetMapping("/getCode")
    @ApiOperation("获取验证码")
    public void getCode(HttpServletResponse response) {
        // 随机生成 4 位验证码
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        // 定义图片的显示大小
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            // 调用父类的 setGenerator() 方法，设置验证码的类型
            lineCaptcha.setGenerator(randomGenerator);
            // 输出到页面
            lineCaptcha.write(response.getOutputStream());
            // 打印日志
            log.info("生成的验证码:{}", lineCaptcha.getCode());
            // 关闭流
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /*
     * 系统管理页面  员工的查询，添加，修改，禁用或者启用
     *
     * */

    /*
    * 员工分页查询
    * */
    @GetMapping("/employeeByPage")
    @ApiOperation("员工分页查询")
    public Result<PageResultVO> selectEmployeeByPage(EmployeePageDTO employeePageDTO) {
          return employeeService.selectEmployeeByPage(employeePageDTO);

    }

    /*
    * 添加员工
    * */
    @PostMapping("/insertEmployee")
    @ApiOperation("添加员工")
    public Result insertEmployee(@RequestBody InsertEmployeeDTO insertEmployeeDTO  ) {

        employeeService.insertEmployee(insertEmployeeDTO);

        return Result.success();

    }
    /*
    * 根据id查询员工
    * */
        @GetMapping("/selectEmployeeById/{id}")
    @ApiOperation("根据id查询员工")
    public Employee selectEmployeeById(@PathVariable("id") Long id) {

        return employeeService.selectEmployeeById(id);
    }

    /*
    * 修改员工
    * */
    @PutMapping("/updateEmployee")
    @ApiOperation("修改员工")
    public Result updateEmployee(@RequestBody UpdateEmployeeDTO updateEmployeeDTO  )  {

        employeeService.updateEmployee(updateEmployeeDTO);
        return Result.success();

    }

    /*
    * 改变员工状态 1启用，0禁用
    * */
    @PutMapping("/updateEmployeeStatus/{status}")
    @ApiOperation("改变员工状态 1启用，0禁用")
    public Result updateEmployeeStatus(@PathVariable("status") Integer status, @RequestParam("id") Long id) {

        employeeService.updateEmployeeStatus(status, id);
        return Result.success();
    }
}
